# @Time    : 2020-07-03 16:34
# @Author  : peng
# @File    : scp.py 发布远端机器
import json
import logging
import os
import pipes
import subprocess
from pathlib import Path

from scp import SCPClient
import paramiko

from gray_apps.models import DeployOpt
from core import sword

logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)

"""发布到远端机器 ssh 连接 暂无"""


# 定义一个专门发布项目的路径 方便管理

# web_apps = "/opt/web_apps/"
# scp_web_apps = "/opt/webapps/"


def get_config():
    json_path = '/'.join([os.getcwd(), 'config.json'])
    with open(json_path, "r") as f:
        jsons = json.load(f)
        local_path = jsons['local']['path']
        remote_path = jsons['remote']['path']
        return local_path, remote_path


def get_jar_name(dirs):
    jar_file = None
    jar_file_path = None
    dirs = dirs + "/target"
    exists = Path(dirs).exists()
    if exists:
        listdir = Path(dirs)

        for file in listdir.iterdir():
            logging.info(file.name)
            if file.name.endswith(".jar") and 'sources.jar' not in file.name:
                jar_file = file.name
                jar_file_path = '/'.join([dirs, jar_file])
                return jar_file, jar_file_path
    else:
        logging.info("no such file")
    return jar_file, jar_file_path


# 本地部署
def deploy(dirs):
    jar_file, jar_file_path = get_jar_name(dirs)
    if jar_file is not None and jar_file_path is not None:
        sh(jar_file_path, jar_file)
    else:
        logging.info('get jar error')


def sh(_file, jar_file):
    sh_cwd = os.getcwd() + "/sh/"
    # 这个不用每次 chmod 可放到 sh 里
    #sh_chmod(sh_cwd)
    run(_file, jar_file, sh_cwd)


def run(_file, jar_file, sh_cwd):
    local_pth, remote_path = get_config()
    run_args = ['bash', 'deploy.sh', local_pth, _file, jar_file]
    sword.execute_cmd(run_args, cwd=sh_cwd, timeout=300, pip=False)


def sh_chmod(sh_cwd):
    sword.execute_cmd(['chmod', '+x', 'deploy.sh'], cwd=sh_cwd, timeout=300, pip=False)


def scp(host, port, username, password, remote_path, file_path):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    ssh_client.connect(host, port, username, password)
    scp_client = SCPClient(ssh_client.get_transport(), socket_timeout=15.0)
    try:
        scp_client.put(file_path, remote_path)
    except FileNotFoundError as e:
        logging.info(e)
        logging.info("not found local file {}".format(file_path))
    else:
        logging.info("scp {} remote---> host {} successful!".format(file_path, host))
    ssh_client.close()


def scp_run(list_dpl, _first, git_root, opt_addr, git_addr):
    host = list_dpl.host
    port = list_dpl.port
    username = list_dpl.username
    password = list_dpl.password
    _id = list_dpl.id

    if _first is None or _first == 'yes':
        # 先scp脚本到远端再执行脚本
        file = os.getcwd() + "/sh/scp_deploy.sh"
        remote_path = "/opt/sh/"
        scp(host, port, username, password, remote_path, file)
        scp_command(git_root, opt_addr, git_addr, host, port, username, password)
        # 回写 first 状态
        DeployOpt.objects.filter(id=_id).update(opt_scp_first='no')
    else:
        scp_command(git_root, opt_addr, git_addr, host, port, username, password)


def scp_command(git_root, opt_addr, git_addr,
                host, port, username, password, ):
    remote_path = "/opt/sh/scp_deploy.sh"
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    ssh_client.connect(host, port, username, password)
    local_pth, remote_app_path = get_config()
    try:
        cmd = ' '.join(['bash', remote_path, remote_path, git_root, opt_addr, git_addr, remote_app_path])
        logging.info('CMD {}'.format(cmd))
        stdin, stdout, stderr = ssh_client.exec_command(cmd)
        result = stdout.read()
        logging.info(str(result, 'utf-8'))
        logging.info("===============REMOTE DONE===============")
    except FileNotFoundError as e:
        logging.info(e)
    ssh_client.close()


def ssh(opt_host):
    ssh_args = ['ssh@root', opt_host]
    logging.info("ssh to remote : --->".format("暂无"))
